﻿using Bmz.IM.Communication;
using Bmz.IM.Model;
using Bmz.Infrastructure.Util;
using DirectX.Capture;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Bmz.IM.Client
{
    public partial class ChatForm : BaseForm
    {
        FriendVO firendInfo = null;
        public ChatForm(FriendVO firendInfo)
        {
            InitializeComponent();
            this.firendInfo = firendInfo;
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            MessageVO messageVO = new MessageVO()
            {
                Type = StructMessageType.Chat,
                Content = txtSendMessage.Text,
                FromUserId = ClientEngineContext.Current.CurrentUser.UserId,
                FromIp = ClientEngineContext.Current.CurrentUser.Ip,
                FromPort = ClientEngineContext.Current.CurrentUser.Port,
                ToUserId = firendInfo.UserId,
                ToIp = firendInfo.Ip,
                ToPort = firendInfo.Port
            };
            ClientEngineContext.Current.SendMessageUdp(messageVO);
            ShowMessage(messageVO);
        }

        public void ShowMessage(MessageVO messageVO)
        {
            if (this.InvokeRequired)
            {
                Action<MessageVO> showMessageInRichTextBox = ShowMessage;
                this.Invoke(showMessageInRichTextBox, messageVO);
            }
            else
            {
                string userName = string.Empty;
                if (messageVO.FromUserId == firendInfo.UserId)
                    userName = firendInfo.UserName;
                else
                {
                    userName = ClientEngineContext.Current.CurrentUser.UserName;
                    txtSendMessage.Text = string.Empty;
                }
                rtbShowMessage.AppendText(userName + "  " + DateTime.Now + ":");
                rtbShowMessage.AppendText(Environment.NewLine);
                rtbShowMessage.AppendText(messageVO.Content);
                rtbShowMessage.AppendText(Environment.NewLine);
            }
        }

        private void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (chatFormDict.ContainsKey(firendInfo.UserId))
                chatFormDict.Remove(firendInfo.UserId);
        }
    }
}
